package main

import (
	"flag"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)
// 如何将线上线下的配置文件隔离
type ServerConfig struct {
	Name string
	Port int
	Log  Log
}
type Log struct {
	Id   int
	YAML string
}

func main() {
	//设置文件的名称,文件的路径如何设置

	configPath := flag.String("f", "config/config.yaml", "config file path")
	flag.Parse()
	fmt.Println(*configPath)

	v := viper.New()

	v.SetConfigFile(*configPath)
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}

	serverConfig := ServerConfig{}
	if err := v.Unmarshal(&serverConfig); err != nil {
		panic(err)
	}
	fmt.Println(serverConfig.Log.YAML)

	//result := v.Get("name")
	//fmt.Println(result)

	//viper 的功能， 动态监控变化
	v.WatchConfig()
	v.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("config file change:", in.Name)
		if err := v.ReadInConfig(); err != nil {
			panic(err)
		}

		serverConfig := ServerConfig{}
		if err := v.Unmarshal(&serverConfig); err != nil {
			panic(err)
		}
		fmt.Println(serverConfig.Log.YAML)

	})
	//time.Sleep(time.Second * 1000)
}
